package com.woniu.backstage.intercptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 〈一句话功能简述〉<br> 
 * 〈登陆拦截器〉
 */
public class LoginInterceptor implements HandlerInterceptor {
    //这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //每一个项目对于登陆的实现逻辑都有所区别，我这里使用最简单的session提取manager来验证登陆。
        HttpSession session = request.getSession();
        //这里的manager是登陆时放入session的
        Object manager = session.getAttribute("manager");
        //如果session中没有manager，表示没登陆
        if (manager == null){
            response.sendRedirect("http://localhost:8000/login.html");
            return false;
        }else {
            //如果session里有manager，表示该用户已经登陆，放行，用户即可继续调用自己需要的接口
            return true;
        }
    }
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}